package Part4_URL编程;

import javax.net.ssl.HttpsURLConnection;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.Buffer;

/**
 * ClassName: Demo
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.04.26 23:41
 */
public class urlTest {
    public static void main(String[] args) {
        String str = "https://c-ssl.duitang.com/uploads/blog/202210/12/20221012065034_42db3.jpeg";

        FileOutputStream fos = null;
        InputStream inputStream = null;
        HttpsURLConnection urlConnection = null;

        try {
            URL url = new URL(str);

            System.out.println(url.getProtocol());//协议名
            System.out.println(url.getPort());//端口
            System.out.println(url.getHost());//ip
            System.out.println(url.getPath());//文件路径
            System.out.println(url.getFile());//文件名
            System.out.println(url.getQuery());//参数列表

            urlConnection = (HttpsURLConnection) url.openConnection();

            inputStream = urlConnection.getInputStream();

            File file = new File("url_file.jpeg");
            fos = new FileOutputStream(file);

            byte[] buffer = new byte[1024];
            int len;
            while ((len=inputStream.read(buffer))!=-1){
                fos.write(buffer, 0, len);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭资源
            try {
                fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            urlConnection.disconnect();
        }
    }
}
